package com.beidouin.GnssMain;

import android.os.Environment;
import android.util.Log;


import com.beidouin.GnssMain.models.PilotInfo;
import com.beidouin.GnssMain.sample.Application;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.beidouin.GnssMain.utils.Base64utils.getFromBase64;

/**
 * Created by Ziji on 2017/7/25.
 */

public class FileManager {

    private int FileStreamSta= NORMAL;//0-正常 1-录制 2-回放
    private static final int storageSel = 1;
    private boolean isNewData=false;
    private boolean playbackFlag=false;

    private int recordTime;
    private int replayTime;
    private int wholeTime;

    public int addRecordTime(){
        recordTime++;
        return recordTime;
    }
    public int getReplayTime(){return replayTime;}
    public int getRecordTime(){return recordTime;}
    public int getWholeTime(){return wholeTime;}
    public boolean getPlaybackFlag(){return playbackFlag;}


    public int get_FileStreamSta(){return FileStreamSta;}
    public final static int ISRECORDING=1;
    public final static int ISPLAYING=2;
    public final static int NORMAL=0;



    public static List<String> scenarioNameList = new ArrayList<String>();//nmea数据
    public static List<String> scenarioNameList2 = new ArrayList<String>();//原始观测量
    public static List<String> scenarioNameList3 = new ArrayList<String>();//星历数据

    private FileInputStream inputStream;
    private FileOutputStream outputStream;

    private FileInputStream inputStream2;
    private FileOutputStream outputStream2;

    private FileInputStream inputStream3;
    private FileOutputStream outputStream3;

    private BufferedReader bufferedReader;
    private BufferedReader bufferedReader2;
    private BufferedReader bufferedReader3;
    private String fileName = "";
    private String fileName2 = "";
    private String fileName3 = "";

    private byte[] EPHDATA=new byte[0];
    //private RandomAccessFile randomAccessFile;
    //private int filePos=0;

    private static FileManager sInstance = new FileManager();
    public static FileManager getInstance() { return sInstance; }

    public boolean get_isNewData(){return isNewData;}
    public void Finish_sleep(){isNewData=false;}



    // ---------------used for recording-----------------
    public String MakeFileName() {
        String name = PilotInfo.getInstance().changeDateToUTC() + "_" + PilotInfo.getInstance().changeTimeToUTC() + ".scene";
        name = name.replace(':', '-');
        return name;
    }
    public String MakeFileName2() {
        String name = PilotInfo.getInstance().changeDateToUTC() + "_" + PilotInfo.getInstance().changeTimeToUTC() + ".bin";
        name = name.replace(':', '-');
        return name;
    }
    public String MakeFileName3() {
        String name = PilotInfo.getInstance().changeDateToUTC() + "_" + PilotInfo.getInstance().changeTimeToUTC() + ".eph";
        name = name.replace(':', '-');
        return name;
    }

    public boolean StartRecording() {

        boolean ret = true;
        try {
            String filename = MakeFileName();
            File file = CreateFile(filename);
            outputStream = new FileOutputStream(file);
            scenarioNameList.add(filename);
            this.fileName = filename;

            String filename2 = MakeFileName2();
            File file2 = CreateFile2(filename2);
            outputStream2 = new FileOutputStream(file2);
            scenarioNameList2.add(filename2);
            this.fileName2 = filename2;

            String filename3 = MakeFileName3();
            File file3 = CreateFile3(filename3);
            outputStream3 = new FileOutputStream(file3);
            scenarioNameList3.add(filename3);
            this.fileName3 = filename3;
            FileStreamSta=ISRECORDING;
            recordTime=0;
        } catch (Exception e) {
            ret = false;
            e.printStackTrace();
        }
        return ret;
    }

    public boolean StopRecording() {
        try {
            outputStream.close();
            outputStream = null;
            fileName = "";

            outputStream2.close();
            outputStream2 = null;
            fileName2 = "";

            outputStream3.close();
            outputStream3 = null;
            fileName3 = "";

            FileStreamSta=NORMAL;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean SaveData(String line, boolean isStart) {
        try {
            outputStream.write(line.getBytes());
        }catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean SaveData2(String line, boolean isStart) {
        try {
            outputStream2.write(line.getBytes());
        }catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public boolean SaveData3(String line, boolean isStart) {
        try {
            outputStream3.write(line.getBytes());
        }catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    // ---------------used for replaying-----------------

    public boolean StartReplaying(String filename) {
        if (filename == null)
            return false;
        try {
            File file = CreateFile(filename);
            File file2 = CreateFile2(filename.replace(".scene",".bin"));
            File file3 = CreateFile3(filename.replace(".scene",".eph"));
            if (file == null) {
                return false;
            }
            if (file2 == null) {
                return false;
            }
            if (file3 == null) {
                return false;
            }
            inputStream = new FileInputStream(file);
            inputStream2 = new FileInputStream(file2);
            inputStream3 = new FileInputStream(file3);

            // randomAccessFile=new RandomAccessFile(file2,"r");
            if (inputStream == null) {
                return false;
            }
            if (inputStream2 == null) {
                return false;
            }
            if (inputStream3 == null) {
                return false;
            }
            /*f (randomAccessFile == null) {
                return false;
            }*/
            bufferedReader = new BufferedReader(new FileReader(file));
            bufferedReader.mark((int)file.length());
            bufferedReader2 = new BufferedReader(new FileReader(file2));
            bufferedReader2.mark((int)file2.length());
            bufferedReader3 = new BufferedReader(new FileReader(file3));
            bufferedReader3.mark((int)file3.length());
            wholeTime = ReadReplayLength();
            replayTime=0;
            bufferedReader.reset();
            bufferedReader2.reset();
            bufferedReader3.reset();
            this.fileName = filename;
            this.fileName2 = filename.replace(".scene",".bin");
            this.fileName3 = filename.replace(".scene",".eph");
            EPHDATA=ReadFile3();
            FileStreamSta=ISPLAYING;
            isNewData=true;
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }
        return true;
    }

    public int ReadReplayLength() {
        int Time=1;
        String str;
        do {
            try {
                //end of the file
                if ((str = bufferedReader.readLine()) == null) {
                    return  Time;
                }
                //new second flag
                if (str.equals("[new second]")) {
                    ++Time;
                }
            } catch (IOException e) {
            }
        } while (true);
    }

    public boolean StopReplaying() {
        try {
            fileName = "";
            inputStream.close();
            bufferedReader.close();
            fileName2 = "";
            inputStream2.close();
            bufferedReader2.close();
            fileName3 = "";
            inputStream3.close();
            bufferedReader3.close();
            //randomAccessFile.close();
            //filePos=0;
            EPHDATA=new byte[0];
            FileStreamSta=NORMAL;
            isNewData=false;
        } catch (IOException e) {
            Log.e("login activity", "Can not stop reading file: " + e.toString());
            return false;
        }
        return true;
    }

    public byte[] ReadFile() throws IOException {
        String str;
        str=new String();
        try {
            //end of the file
            if ((str = bufferedReader.readLine()) == null) {
                StopReplaying();
                FileStreamSta=NORMAL;
                playbackFlag=true;
                return new String("\r\n").getBytes();
            }
            //new second flag
            else if (str.equals("[new second]")) {
                ++replayTime;
                isNewData=true;
                return new String("\r\n").getBytes();
            }
            else {
                str = str + "\r\n";
                return str.getBytes();
            }
        } catch (IOException e) {
            return new String("\r\n").getBytes();
        }
    }


    public byte[] ReadFile2() throws IOException {
        String str=new String();
        try {
            //end of the file
            if ((str = bufferedReader2.readLine()) == null) {
                StopReplaying();
                FileStreamSta=NORMAL;
                playbackFlag=true;
                return new String("\r\n").getBytes();
            }
            else {
                byte[] bytes = getFromBase64(str);
                return bytes;
            }
        } catch (IOException e) {
            return new String("\r\n").getBytes();
        }
    }

    public byte[] ReadFile3() throws IOException {
        String str=new String();
        try {
            //end of the file
            if ((str = bufferedReader3.readLine()) == null) {
                return new String("Fail to read").getBytes();
            }
            else {
                byte[] bytes = getFromBase64(str);
                return bytes;
            }
        } catch (IOException e) {
            return new String("Fail to read").getBytes();
        }
    }

    public byte[] getEPHDATA()
    {
        if(EPHDATA==null)
            return "Fail to read".getBytes();
        else
            return EPHDATA;
    }

    private File CreateFile(String filename) {
        String filepath = getSdCardPath() + "iN6100_data/NMEA/";
        if (isDirectionExist(filepath) == false) {
            String mainpath = getSdCardPath() + "iN6100_data";
            File file=new File(mainpath);
            file.mkdir();
        }
        isDirectionExist(filepath);
        String name = filepath + filename;
        return new File(name);
    }

    private File CreateFile2(String filename) {
        String filepath = getSdCardPath() + "iN6100_data/BINNARY/";
        if (isDirectionExist(filepath) == false) {
            String mainpath = getSdCardPath() + "iN6100_data";
            File file=new File(mainpath);
            file.mkdir();
        }
        isDirectionExist(filepath);
        String name = filepath + filename;
        return new File(name);
    }

    private File CreateFile3(String filename) {
        String filepath = getSdCardPath() + "iN6100_data/EPHEMERIS/";
        if (isDirectionExist(filepath) == false) {
            String mainpath = getSdCardPath() + "iN6100_data";
            File file=new File(mainpath);
            file.mkdir();
        }
        isDirectionExist(filepath);
        String name = filepath + filename;
        return new File(name);
    }

    public void initFileList() {
        String filepath0 = getSdCardPath() + "iN6100_data";
        String filepath1 = getSdCardPath() + "iN6100_data/NMEA";
        String filepath2 = getSdCardPath() + "iN6100_data/BINNARY";
        String filepath3 = getSdCardPath() + "iN6100_data/EPHEMERIS";
        File specItemDir0 = new File(filepath0);
        File specItemDir1 = new File(filepath1);
        File specItemDir2 = new File(filepath2);
        File specItemDir3 = new File(filepath3);
        if (!specItemDir0.exists()) {
            specItemDir0.mkdir();
        }
        if (!specItemDir1.exists()) {
            specItemDir1.mkdir();
        }
        if (!specItemDir2.exists()) {
            specItemDir2.mkdir();
        }
        if (!specItemDir3.exists()) {
            specItemDir3.mkdir();
        }
        if (!specItemDir0.exists()) {
            return;
        }
        if (!specItemDir1.exists()) {
            return;
        }
        if (!specItemDir2.exists()) {
            return;
        }
        if (!specItemDir3.exists()) {
            return;
        }
        final File[] fileList = specItemDir1.listFiles();
        final File[] fileList2 = specItemDir2.listFiles();
        final File[] fileList3 = specItemDir2.listFiles();
        String filename;
        String filename2;
        String filename3;
        int idx;
        int idx2;
        int idx3;
        for (File file : fileList) {
            filename = file.getPath();
            //delete path
            idx = filename.lastIndexOf("/");
            if (idx == -1) {
                continue;
            }
            filename = filename.substring(idx + 1);
            //check .scene
            if (filename.endsWith(".scene")) {
                scenarioNameList.add(filename);
            }
        }
        for (File file2 : fileList2) {
            filename2 = file2.getPath();
            //delete path
            idx2 = filename2.lastIndexOf("/");
            if (idx2 == -1) {
                continue;
            }
            filename2 = filename2.substring(idx2 + 1);
            //check .scene
            if (filename2.endsWith(".bin")) {
                scenarioNameList2.add(filename2);
            }
        }
        for (File file3 : fileList3) {
            filename3 = file3.getPath();
            //delete path
            idx3 = filename3.lastIndexOf("/");
            if (idx3 == -1) {
                continue;
            }
            filename3 = filename3.substring(idx3 + 1);
            //check .scene
            if (filename3.endsWith(".eph")) {
                scenarioNameList3.add(filename3);
            }
        }
    }


    public void DeleteFile(String filename) {
        File file = new File(getSdCardPath() + "iN6100_data/NMEA/", filename);
        file.delete();
        scenarioNameList.remove(filename);
        File file2 = new File(getSdCardPath() + "iN6100_data/BINNARY", filename.replace(".scene",".bin"));
        file2.delete();
        scenarioNameList2.remove(filename.replace(".scene",".bin"));
        File file3 = new File(getSdCardPath() + "iN6100_data/EPHEMERIS", filename.replace(".scene",".eph"));
        file3.delete();
        scenarioNameList3.remove(filename.replace(".scene",".eph"));
    }

    //获取SD卡根目录
    public String getSdCardPath() {
        if (storageSel == 1)
            return Environment.getExternalStorageDirectory().getPath()+ "/";
        else if (storageSel == 2)
            return "/storage/emulated/0/";
        else
            return Application.getInstance().getFilesDir() + "/";
    }

    //判断文件夹是否存在,如果不存在则创建文件夹
    public boolean isDirectionExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        return file.exists();
    }



}
